package com.ruiyangwang.ListenBook.servlet.user;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruiyangwang.ListenBook.util.Log;
import com.ruiyangwang.ListenBook.viewObject.UserV0;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author syzygy
 * @date 2022/08/01 09:54
 **/
@WebServlet("/studio/user/current-user.json")
public class UserJsonDoServlet extends HttpServlet {
    private final ObjectMapper objectMapper = new ObjectMapper();
    static class CurrentUserView {

        public UserV0 currentUser;
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        CurrentUserView view = new CurrentUserView();
        HttpSession session = req.getSession(false);
        if (session != null) {
            view.currentUser = (UserV0) session.getAttribute("currentUser");
        }
        String json = objectMapper.writer().writeValueAsString(view);
        Log.println("JSON 序列化的结果" + json);

        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        PrintWriter printWriter = resp.getWriter();
        Log.println("写入响应体中");
        printWriter.println(json);

    }
}